package com.soft.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/Authcode")
public class AuthcodeServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int wdith = 100;
        int height = 35;

    //在内存中创建一个图片
        BufferedImage image = new BufferedImage(wdith, height, BufferedImage.TYPE_3BYTE_BGR);

        Graphics g = image.getGraphics();
        //设置图片的背景颜色,底色为白色
        g.setColor(Color.white);
        g.fillRect(0,0,wdith,height);

        //数字颜色
        g.setColor(Color.blue);
        g.drawRect(0,0,wdith-1,height-1);

        Random random = new Random();
        String str = "123";
        StringBuffer sb = new StringBuffer();
        for (int i=1; i<=4; i++) {
            int i1 = random.nextInt(str.length());
            char c = str.charAt(i1);
            sb.append(c);
            g.drawString(c+"",wdith/5*i+5,height/2);
        }
        String s = sb.toString();
        req.getSession().setAttribute("yanzhengma",s);

        for (int i = 0 ; i < 5 ; i++) {
            //干扰线颜色黑色
            g.setColor(Color.black);
            int x1 = random.nextInt(wdith);
            int x2 = random.nextInt(wdith);
            int y1 = random.nextInt(height);
            int y2 = random.nextInt(height);
            g.drawLine(x1,y1,x2,y2);
        }
    //把图片写给浏览器
        ImageIO.write(image,"jpg",resp.getOutputStream());
        System.out.println("图片生成成功");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
